package xxx

import (
	"fmt"
	shs "gitee.com/asphodelus_dev/simple-hashtable-storage"
	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v3"
)

var Db *shs.StorageEngine

type (
	ErrorResponse struct {
		Error       bool
		FailedField string
		Value       interface{}
	}
	XValidator struct {
		validator *validator.Validate
	}

	GlobalErrorHandlerResp struct {
		Success bool   `json:"success"`
		Message string `json:"message"`
	}
)

func OpenDb() {
	opt := shs.Options{DirPath: "data", DataIndex: &LinkedListDataIndex{}}
	engine, err := shs.NewStorageEngine(opt)
	if err != nil {
		panic(err)
	}
	Db = engine
}

// This is the validator instance
// for more information see: https://github.com/go-playground/validator
var (
	validate    = validator.New()
	MyValidator = &XValidator{
		validator: validate,
	}
)

func (v XValidator) Validate(data interface{}) []ErrorResponse {
	validationErrors := []ErrorResponse{}

	errs := validate.Struct(data)
	if errs != nil {
		for _, err := range errs.(validator.ValidationErrors) {
			// In this case data object is actually holding the User struct
			var elem ErrorResponse

			elem.FailedField = err.Field() // Export struct field name
			elem.Value = err.Value()       // Export field value
			elem.Error = true

			validationErrors = append(validationErrors, elem)
		}
	}

	return validationErrors
}

func a() int {
	return Add(1, 1)
}

func b() {
	fmt.Printf("%v\n", fmt.Sprintf("%v", 1+1))
}

func Add(a int, b int) int {
	return a + b
}

func IndexHandler(c fiber.Ctx) error {
	return c.SendString(fmt.Sprintf("%v", a()))
}

func FooHandler(c fiber.Ctx) error {
	return c.SendString("xxx")
}

func BarGetHandler(c fiber.Ctx) error {
	key := c.Params("key")
	value, err := Db.Get([]byte(key))
	if err != nil {
		return err
	}

	return c.SendString(string(value))
}

func BarPutHandler(c fiber.Ctx) error {
	key := c.Params("key")
	value := c.Params("val")
	res := "ok"
	err := Db.Insert([]byte(key), []byte(value))
	if err != nil {
		return err
	}
	if err != nil {
		return err
	}
	return c.SendString(res)
}
